﻿using Autofac;
using Common;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DBContext;
using EV.EventBus;
using Microsoft.Win32;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using ZoneLine.Common;
using ZoneLine.Models;
using ZoneLine.Models.PackageModel;
using ZoneLine.Models.PrintModeConfig;
using ZoneLine.Models.StationConfig;
using ZoneLine.Views;
using ZoneLine.Views.converts;

namespace ZoneLine.ViewModels
{
    public class PackageBoxViewModel : ObservableObject
    {
        private IModelDAL _dal;

        private Speaker _speaker;

        public PackageBoxViewModel(IModelDAL dal)
        {
            _speaker = Speaker.GetSpeaker();

            _dal = dal;
            PackageScanConfig = _dal.GetModel<PackageScanBarConfig>(p => true);

            //Init();
            ScanLinkCmd.Execute("Open");

            var packageConfig = _dal.GetModel<PackagePrintConfig>(p => true);
            if (packageConfig == null)
            {
                _dal.AddModel(new PackagePrintConfig());
                packageConfig = new PackagePrintConfig();
            }

            #region 动态生成描述 Add 2025-02-28
            packageConfig.ProductInfo = @"{0}{1}{2}{3}滑柱总成";
            var modelConvert = new ModelConvert();
            var modelStr = modelConvert.Convert(Cache.Model, null, "", null);

            var workDirecitionConvert = new WorkDirecitionConvert();
            var workDirecitionStr = workDirecitionConvert.Convert(Cache.WorkDirection, null, "", null);

            packageConfig.ProductInfo = string.Format(packageConfig.ProductInfo, modelStr, Cache.CurrentProductType, (Cache.IsHopStaion ? "后" : Cache.IsQopStaion ? "前" : ""),workDirecitionStr);

            packageConfig.BatchCode = DateTime.Now.ToString("yyMMdd");

            //物料编码
            packageConfig.MaterialCode = SysCfg.GetBoxCodeMaterialCode(Cache.IsQopStaion ? 1 : Cache.IsHopStaion ? 2 : 0, Cache.CurrentProductType, Cache.WorkDirection);
            #endregion


            PackageCfg = packageConfig;

            Task.Run(() =>
            {
                FreshPageTemp();
            });
        }

        private PackageScanBarConfig _packageScanConfig;

        public PackageScanBarConfig PackageScanConfig
        {
            get { return _packageScanConfig; }
            set => SetProperty(ref _packageScanConfig, value);
        }

        private PackagePrintConfig _packageCfg;

        public PackagePrintConfig PackageCfg
        {
            get { return _packageCfg; }
            set => SetProperty(ref _packageCfg, value);
        }

        private string _boxCode;

        public string BoxCode
        {
            get { return _boxCode; }
            set => SetProperty(ref _boxCode, value);
        }

        private List<PackageTempModel> _inPackageAbsLst;

        public List<PackageTempModel> InPackageAbsLst
        {
            get { return _inPackageAbsLst; }
            set => SetProperty(ref _inPackageAbsLst, value);
        }

        private RelayCommand _selectedPackageTemplateCmd;

        public RelayCommand SelectPackageTemplateCmd
        {
            get { return _selectedPackageTemplateCmd ?? (_selectedPackageTemplateCmd = new RelayCommand(SelectPackageTemplate)); }
        }

        private void SelectPackageTemplate()
        {
            FileDialog dia = new OpenFileDialog();
            var rlt = dia.ShowDialog();
            string path = string.Empty;
            if (rlt.HasValue && rlt.Value)
            {
                PackageCfg.TemplatePath = dia.FileName;
            }
        }


        private RelayCommand<string> _scanLinkCmd;

        public RelayCommand<string> ScanLinkCmd
        {
            get { return _scanLinkCmd ?? (_scanLinkCmd = new RelayCommand<string>(o => Init(o))); }
        }
        

        private RelayCommand<string> _packageTest;

        public RelayCommand<string> PackageTest
        {
            get { return _packageTest ?? (_packageTest = new RelayCommand<string>(PieceBoxAction)); }
        }

        private RelayCommand _saveCmd;

        public RelayCommand SaveCmd
        {
            get { return _saveCmd ?? (_saveCmd = new RelayCommand(Save)); }
        }

        private void Save()
        {
            //GenerateBoxCode();
            var updateRlt = _dal.UpdateModelSuper(p => true, PackageCfg);
            if (!updateRlt)
            {
                MessageBox.Show("保存失败");
            }
        }

        private RelayCommand _clearBoxCmd;

        public RelayCommand ClearBoxCmd
        {
            get { return _clearBoxCmd ?? (_clearBoxCmd = new RelayCommand(ClearBox)); }
        }

        private void ClearBox()
        {
            var rlt = MessageBox.Show(App.Current.MainWindow, "请确认是否清除当前箱的装箱信息", "提示", MessageBoxButton.YesNo);
            if (rlt == MessageBoxResult.Yes)
            {
                _dal.DeleteModel<PackageTempModel>(p => true);
                FreshPageTemp();
            }
        }

        private RelayCommand _generateBoxCodeCmd;

        public RelayCommand GenerateBoxCodeCmd
        {
            get { return _generateBoxCodeCmd ?? (_generateBoxCodeCmd = new RelayCommand(GenerateBoxCode)); }
        }


        #region 2025-03-06 Add
        //已有箱码继续装箱
        public RelayCommand ContinueBoxUpCmd => new RelayCommand(() =>
        {
            if (InPackageAbsLst.Count > 0)
            {
                HandyControl.Controls.MessageBox.Error("当前列表中存在尚未装箱的产品！", "温馨提示");
                return;
            }

            string boxCode = "";
            AuthView authView = new AuthView(() =>
            {
                ContinueBoxUpView continueBoxUpView = new ContinueBoxUpView(_dal, (arg) =>
                {
                    boxCode = arg;
                });
                continueBoxUpView.ShowDialog();
            });
            authView.ShowDialog();
            //查询装箱信息
            if (boxCode != "")
            {
                var list = _dal.GetModelList<PackageResult>(o => o.BoxCode == boxCode);
                if (list != null && list.Count > 0)
                {
                    var packageTempModels = new List<PackageTempModel>();
                    foreach (var item in list)
                    {
                        var packageTempModel = new PackageTempModel()
                        {
                            AbsCode = item.AbsCode,
                            Code = item.Code,
                            Brand = item.Brand,
                            LeftRight = item.LeftRight,
                            PrintTime = item.PrintTime,
                            BoxCode = item.BoxCode,
                            PackageTime = item.PackageTime,
                        };
                        packageTempModels.Add(packageTempModel);
                    }
                    var res = false;
                    if (packageTempModels.Count > 0)
                    {
                        res = _dal.AddModels<PackageTempModel>(packageTempModels);
                        Logger.Log.Warn($"新增PackageTempModel临时表数据,rls={res},count={packageTempModels.Count}");
                    }

                    if (res)
                    {
                        res = _dal.DeleteModel<PackageResult>(o => o.BoxCode == boxCode);
                        Logger.Log.Warn($"清除PackageResult装箱表数据,rls={res},count={packageTempModels.Count}");
                    }

                    if (res)
                    {
                        FreshPageTemp(); //刷新列表
                    }
                }
            }
            else
            {
                //HandyControl.Controls.MessageBox.Error("箱码为空！","温馨提示");
            }
        });
        #endregion


        private void GenerateBoxCode()
        {
            var modelCount = _dal.GetModelList<PackageTempModel>(p => true).Count;
            if (modelCount == 0)
            {
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:生成失败，当前未进行产品录入！");

                return;
            }
            BoxCode = $"$P{PackageCfg.MaterialCode}$V8000$L{PackageCfg.BatchCode}$Q{PackageCfg.PackageCount}$O$S0$E{PackageCfg.WorkShop}$N{PackageCfg.BoxNum}";
            var codeTemp = $"$P{PackageCfg.MaterialCode}$V8000$L{PackageCfg.BatchCode}$Q{PackageCfg.PackageCount}$O$S0$E{PackageCfg.WorkShop}$N{PackageCfg.BoxNum}";
            if (_dal.GetModelList<PackageTempModel>(p => true).Count != PackageCfg.PackageCount)
            {
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，当前装入产品数量与设定装箱数量不符，设定的装箱数量：{PackageCfg.PackageCount}");
                return;
            }
            if (_dal.CheckExist<PackageResult>(p => p.BoxCode == codeTemp))
            {
                var msg = $"装箱信息:装箱失败，当前信息生成的箱码是【{codeTemp}】,已被装箱过，请修改参数重新生成";
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), msg);
                return;
            }
            else
            {
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:箱码生成成功，当前信息生成的箱码是【{codeTemp}】");
            }

            var models = _dal.GetModelList<PackageTempModel>(p => true);
            if (models.Count >= PackageCfg.PackageCount)
            {
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱成功,当前箱已经装满，箱码:{codeTemp}");
                var listRlt = new List<PackageResult>();
                foreach (var item in models)
                {
                    var packageRlt = new PackageResult()
                    {
                        AbsCode = item.AbsCode,
                        Brand = item.Brand,
                        LeftRight = item.LeftRight,
                        BoxCode = codeTemp,
                        Code = item.Code,
                        PackageTime = item.PackageTime,
                        PrintTime = item.PrintTime,
                    };
                    listRlt.Add(packageRlt);
                }
                _dal.AddModels(listRlt);
                FreshPageTemp();
                PrintBoxCode();
            }
            //if (models.Count > 0)
            //{
            //    var rlt = MessageBox.Show("当前箱装箱未完成，重新生成箱码会丢弃当前箱装箱记录，当前箱工件需要重新扫码装箱，请确认是否执行", "警告", MessageBoxButton.YesNo, MessageBoxImage.Question);
            //    if (rlt != MessageBoxResult.Yes)
            //    {
            //        return;
            //    }
            //    ClearBox();
            //}
        }

        private string _portStatus = "关闭";

        public string PortStatus
        {
            get { return _portStatus; }
            set => SetProperty(ref _portStatus, value);
        }

        private RelayCommand _printBoxCodeCmd;

        public RelayCommand PrintBoxCodeCmd
        {
            get { return _printBoxCodeCmd ?? (_printBoxCodeCmd = new RelayCommand(PrintBoxCode)); }
        }

        private void PrintBoxCode()
        {
            //编码 BM_N7
            //产品描述 CPMS_N7
            //批号 PH_N7
            //数量 SL_N7
            //单位 DW_N7
            //箱号 XH_N7
            //二维码 EWM_N7

            if (string.IsNullOrEmpty(BoxCode))
            {
                MessageBox.Show(App.Current.MainWindow, "请先生成箱码再打印");
                return;
            }
            string CTPM = string.Empty;
            switch (Cache.Model.ToString())
            {
                case "LX":
                    if (((int)Cache.WorkDirection).Equals(1))
                    {
                        CTPM = _dal.GetModel<LXQC_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNoL;
                    }
                    else
                    {
                        CTPM = _dal.GetModel<LXQC_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNoR;
                    }
                    break;

                case "SQ":
                    if (((int)Cache.WorkDirection).Equals(1))
                    {
                        CTPM = _dal.GetModel<SQQC_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartIdentificationCode;
                    }
                    else
                    {
                        CTPM = _dal.GetModel<SQQC_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartIdentificationCode;
                    }
                    break;

                case "BQKH":
                    if (((int)Cache.WorkDirection).Equals(1))
                    {
                        CTPM = _dal.GetModel<BQQC_KH_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNumber;
                    }
                    else
                    {
                        CTPM = _dal.GetModel<BQQC_KH_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNumber;
                    }
                    break;

                case "BQLH":
                    if (((int)Cache.WorkDirection).Equals(1))
                    {
                        CTPM = _dal.GetModel<BQQC_LH_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNo;
                    }
                    else
                    {
                        CTPM = _dal.GetModel<BQQC_LH_Config>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNo;
                    }
                    break;

                case "WL":
                    if (((int)Cache.WorkDirection).Equals(1))
                    {
                        CTPM = _dal.GetModel<WLQCConfig>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNo;
                    }
                    else
                    {
                        CTPM = _dal.GetModel<WLQCConfig>(g => g.ProductType.Equals(Cache.CurrentProductType)).PartNo;
                    }
                    break;

                default:
                    break;
            }
            Task.Run(() =>
            {
                try
                {
                    //BoxCode = $"$P{PackageCfg.MaterialCode}$V8000$L{PackageCfg.BatchCode}$Q{PackageCfg.PackageCount}$O$S0$E{PackageCfg.WorkShop}$N{PackageCfg.BoxNum}";
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"开始打印箱码{BoxCode}");
                    var paras = new Dictionary<string, string>() { { "Code", BoxCode } };
                    paras.Add("CPTM_N7", CTPM);
                    paras.Add("BM_N7", PackageCfg.MaterialCode);
                    paras.Add("CPMS_N7", PackageCfg.ProductInfo);
                    paras.Add("PH_N7", PackageCfg.BatchCode);
                    paras.Add("SL_N7", PackageCfg.PackageCount.ToString());
                    paras.Add("DW_N7", PackageCfg.Unit);
                    paras.Add("XH_N7", PackageCfg.BoxNum.ToString());
                    paras.Add("EWM_N7", BoxCode);
                    PrinterHelper.PrinterLabel(PackageCfg.TemplatePath, PackageScanConfig.Printer, paras);
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"箱码打印成功");
                    ClearCurrentBox();
                    ClearBoxCode();
                    PackageCfg.BoxNum++;
                }
                catch (Exception ex)
                {
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"箱码打印失败:{ex.Message}");
                    Logger.Log.Error(ex, "打印箱码失败");
                }
            });
        }

        private SerialPort _scanSerial;

        private void Init(string cmd)
        {
            if (cmd == "Open")
            {
                Task.Run(() =>
                {
                    //while (PortStatus != "打开")
                    if (PortStatus != "打开")
                    {
                        try
                        {
                            PortStatus = "打开中";
                            if (_scanSerial == null)
                            {
                                _scanSerial = new SerialPort();
                                _scanSerial.PortName = PackageScanConfig.Port;
                                _scanSerial.BaudRate = 115200;
                                _scanSerial.DataBits = 8;
                                _scanSerial.StopBits = StopBits.One;
                                _scanSerial.Parity = Parity.None;
                                _scanSerial.DataReceived += _scanSerial_DataReceived;
                            }
                            _scanSerial.Close();
                            _scanSerial.Open();
                            if (_scanSerial.IsOpen)
                            {
                                PortStatus = "打开";
                                //break;
                            }
                        }
                        catch (Exception ex)
                        {
                            PortStatus = "打开失败，请重试！";
                        }
                        Thread.Sleep(1000);
                    }
                });
            }
            else
            {
                if (_scanSerial != null)
                {
                    _scanSerial?.Close();
                    if (!_scanSerial.IsOpen) PortStatus = "关闭";
                    _scanSerial?.Dispose();
                }
            }
        }

        private int count;

        private void _scanSerial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(200);

            var lenght = _scanSerial.BytesToRead;

            var bytes = new byte[lenght];
            _scanSerial.Read(bytes, 0, lenght);
            var str = Encoding.UTF8.GetString(bytes).Replace("\n", "").Replace("\r", "");
            count++;
            MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"扫码枪收到第{count}个条码:{str}");
            if (Cache.EnterReplaceStatus)
            {
                MessageCenter.PublishAsync(nameof(PackageReplaceViewModel), str);
            }
            else
            {
                if (str.Length < 30)
                {
                    MessageCenter.PublishAsync(nameof(LableCompenstateViewModel), str);
                    MessageCenter.PublishAsync(nameof(WorkSituationViewModel), str);
                    MessageCenter.PublishAsync(nameof(HistoryViewModel), str);
                }
                else if (str.StartsWith("$"))
                {
                    MessageCenter.PublishAsync(nameof(HistoryViewModel), str);
                    MessageCenter.PublishAsync(nameof(ContinueBoxUpView), str);
                }
                else
                {
                    PieceBoxAction(str);
                }
            }
        }

        private bool _inAlarmState;

        /// <summary>
        /// 进入报警状态，需要手动确定才能继续接受扫码
        /// </summary>
        public bool InAlarmState
        {
            get { return _inAlarmState; }
            set => SetProperty(ref _inAlarmState, value);
        }

        private bool _enterAlarmState = false;

        ///将工件进行装箱操作
        private void PieceBoxAction(string code)
        {
            try
            {
                if (InAlarmState)
                {
                    return;
                }
                InAlarmState = true;
                if (_dal.GetModelList<PackageTempModel>(p => true).Count == PackageCfg.PackageCount)
                {
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，已达到设定的装箱数量，请手动点击生成箱码！");
                    return;
                }
                //if (string.IsNullOrEmpty(BoxCode))
                //{
                //    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), "装箱信息:请先生成箱码进行装箱");
                //    return;
                //}
                var (hasWorkRlt, printRlt) = CheckPieceHasWorked(code);
                if (!hasWorkRlt)
                {
                    MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，工件未在生产线加工");
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), "装箱信息:装箱失败，工件未在生产线加工或在生产线加工NG");
                    return;
                }

                var (hasBoxInTemp, boxTemp) = CheckPieceBoxInTemp(code);
                if (hasBoxInTemp)
                {
                    MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，工件已在当前箱");
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，工件已在当前箱装箱过程中，箱码:{boxTemp.BoxCode}");
                    return;
                }

                var (hasBoxed, boxed) = CheckPieceBoxed(code);
                if (hasBoxed)
                {
                    MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，工件已被装箱");
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，工件已被装箱，箱码:{boxed.BoxCode}");
                    return;
                }

                var isSameBrand = CheckIsCurrentBrand(printRlt);
                if (!isSameBrand)
                {
                    MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，型号不同");
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，工件和箱子中的型号不同，当前工件型号:{printRlt.Brand}");
                    return;
                }
                var isSameLs = CheckIsSameLR(printRlt);
                if (!isSameLs)
                {
                    MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，左右不同");
                    MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，工件和箱子中的左右不同，当前工件左右是:{(printRlt.LeftRight == 1 ? "左" : "右")}");
                    return;
                }

                var recordRlt = false;
                var pieceBoxRlt = new PackageTempModel()
                {
                    AbsCode = printRlt.AbsCode,
                    Brand = printRlt.Brand,
                    LeftRight = printRlt.LeftRight,
                    PrintTime = printRlt.PrintTime,
                    Code = printRlt.Code,
                };
                if (pieceBoxRlt != null)
                {
                    pieceBoxRlt.BoxCode = BoxCode;
                    pieceBoxRlt.PackageTime = DateTime.Now;
                    recordRlt = _dal.AddModel(pieceBoxRlt);
                    if (recordRlt)
                    {
                        FreshPageTemp();
                        var count = InPackageAbsLst.Count;
                        MessageCenter.PublishAsync(nameof(Speaker), $"装箱成功，第{count}个产品");
                        MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱成功，这是该箱子的第{count}个产品");
                        var models = _dal.GetModelList<PackageTempModel>(p => true);
                        if (models.Count == PackageCfg.PackageCount)
                        {
                            MessageCenter.PublishAsync(nameof(Speaker), $"产品已够数，开始自动打印！");
                            MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱成功,设定箱量产品已够数，开始自动打印！");

                            GenerateBoxCode();
                        }
                        InAlarmState = false;
                    }
                    else
                    {
                        MessageCenter.PublishAsync(nameof(Speaker), "装箱失败，记录装箱数据到过程数据失败");
                        MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱失败，记录装箱数据到过程数据失败");
                    }
                }

                //检测当前箱子里有多少工件
                FreshPageTemp();
            }
            catch (Exception ex)
            {
                MessageCenter.PublishAsync(nameof(Speaker), "装箱异常");
                MessageCenter.PublishAsync(nameof(PackageBoxViewModel), $"装箱信息:装箱异常{ex.Message}");
            }
        }

        private RelayCommand _freshCurrentBoxCmd;

        public RelayCommand FreshCurrentBoxCmd
        {
            get { return _freshCurrentBoxCmd ?? (_freshCurrentBoxCmd = new RelayCommand(FreshPageTemp)); }
        }

        private void FreshPageTemp()
        {
            InPackageAbsLst = _dal.GetModelList<PackageTempModel>(p => true);
        }

        private void ClearBoxCode()
        {
            BoxCode = string.Empty;
        }

        private void ClearCurrentBox()
        {
            //日志记录
            var list = _dal.GetModelList<PackageTempModel>(p => p.Id > 0);
            Logger.Log.Warn($"ClearCurrentBoxMethod，BoxCode：{BoxCode} PackageTempModelListCount：{list.Count}");
            Logger.Log.Warn($"ClearCurrentBoxMethod，BoxCode：{BoxCode} PackageCfg：{JsonConvert.SerializeObject(PackageCfg)}，PackageTempModelList：{JsonConvert.SerializeObject(list)}");
            _dal.DeleteModel<PackageTempModel>(p => p.Id > 0);
        }

        /// <summary>
        /// 检测条码工件是否工作加工并加工完成
        /// </summary>
        private (bool, AbsPrintResult) CheckPieceHasWorked(string code)
        {
            var printResult = _dal.GetModel<AbsPrintResult>(p => p.Code == code);
            if (printResult == null)
            {
                return (false, null);
            }
            else
            {
                return (true, printResult);
            }
        }

        /// <summary>
        /// 检查该条码的工件是否已经在装箱中间表
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private (bool, PackageTempModel) CheckPieceBoxInTemp(string code)
        {
            var packageTemp = _dal.GetModel<PackageTempModel>(p => p.Code == code);
            return (packageTemp != null, packageTemp);
        }

        /// <summary>
        /// 检查该条码的工件是否已经装箱成功
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private (bool, PackageTempModel) CheckPieceBoxed(string code)
        {
            var packageTemp = _dal.GetModel<PackageResult>(p => p.Code == code);
            return (packageTemp != null, packageTemp);
        }

        /// <summary>
        /// 根据条码检测当前这个工件和原有的是不是一个品牌
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool CheckIsCurrentBrand(AbsPrintResult abs)
        {
            var model = _dal.GetModel<PackageTempModel>(p => true);

            //当前是个空箱，不用检测型号
            if (model == null)
            {
                return true;
            }
            return model.Brand == abs.Brand;
        }

        /// <summary>
        /// 根据条码检测当前这个工件和原有的是不是左右一样
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private bool CheckIsSameLR(AbsPrintResult abs)
        {
            return abs.Brand == Cache.Model.ToString() && (int)Cache.WorkDirection == abs.LeftRight;
        }

        private void GetLatest()
        {
            PackageArgsConfig packageArgs = _dal.GetModel<PackageArgsConfig>(gm => gm.Status.Equals(1));
            PackageCfg.MaterialCode = packageArgs.MaterialCode;
            PackageCfg.BatchCode = packageArgs.BatchCode;
            PackageCfg.PackageCount = packageArgs.PackageCount;
            PackageCfg.BoxNum = packageArgs.BoxNum;
            PackageCfg.WorkShop = packageArgs.WorkShop;
        }
    }
}